package com.oracle.filter;

import com.oracle.entity.LoginTeacher;
import com.oracle.pojo.Teacher;
import com.oracle.util.JJWTUtilsTeacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, ServletException, IOException {
        //获取token
        String usertoken = request.getHeader("Token");
        if (!StringUtils.hasText(usertoken)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }

        //解析用户给的token 有可能是非法token 如果是非法token 异常处理
        String username = null;
        try {
            Teacher teacher = JJWTUtilsTeacher.decode(usertoken);
            username = teacher.getTeachNum();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //从redis中获取用户信息
        String redisToken = stringRedisTemplate.opsForValue().get("login:user:" + username);
        if(StringUtils.isEmpty(redisToken)){
            throw new RuntimeException("用户未登录");
        }

        Teacher redisUser = JJWTUtilsTeacher.decode(redisToken);
        LoginTeacher user = new LoginTeacher(redisUser);

        //封装Authentication对象存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user,null,null);

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
